package com.gxa.controller;

import com.gxa.dto.ResultDto;
import com.gxa.pojo.User;
import com.gxa.util.Response;
import com.gxa.util.SendEmail;
import com.gxa.validator.MyValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class SmsController {

    @Autowired
    private SendEmail send;
    @Autowired
    private MyValidator validator;

    /**
     * 发送短信
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sms/msg")
    @ResponseBody
    public ResultDto sendEmail(@RequestBody User user, HttpSession session){
        //校验手机号
        validator.validate(user);
        //获取验证码
        String code = send.getCode();
        session.setAttribute("code",code);
        session.setAttribute("phone",user.getUserPhone());
        Boolean bool = send.sendEmail(user.getUserPhone(), code);
        if(bool){
           return Response.success(200,"发送成功");
        }
        return Response.error(1001,"发送失败");
    }

    @PostMapping("/sms/check")
    @ResponseBody
    public ResultDto checkCodeAndPhone(String phone,String code,HttpSession session){
        // 先获取session中的验证码
        String vcode = (String) session.getAttribute("code");
        String phone1 = (String) session.getAttribute("phone");
        if (code.equals(vcode) && phone.equals(phone1)) {
            return Response.success("验证码正确！");
        }
        return Response.error(1002, "验证码错误！");
    }
}
